package com.qingyun.system.controller;

import com.qingyun.system.common.result.Result;
import com.qingyun.system.model.entity.Message;
import com.qingyun.system.model.form.MessageForm;
import com.qingyun.system.model.query.MessageQuery;
import com.qingyun.system.model.vo.MessageVO;
import com.qingyun.system.model.vo.PageVO;
import com.qingyun.system.service.MessageService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.modelmapper.ModelMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("api/v1/message")
@Slf4j
@Tag(name = "08.聊天记录管理模块")
public class MessageController {

    @Resource
    private MessageService messageService;

    @Resource
    private ModelMapper modelMapper;

    /**
     *   分页查询聊天记录
     * @param messageQuery 查询参数
     * @return 聊天记录列表
     */
    @Operation(summary = "分页查询聊天记录")
    @PostMapping("/query")
    public Result<Object> queryMessageList(@RequestBody MessageQuery messageQuery){
        PageVO<MessageVO> messageList = messageService.queryMessageList(messageQuery);
        return Result.success(messageList);
    }

    /**
     *  新增聊天记录
     * @param messageForm 聊天记录表单
     * @return 新增结果
     */
    @Operation(summary = "新增聊天记录")
    @RequestMapping(name = "/save",method = {RequestMethod.POST})
    public Result<Object> addMessage(@RequestBody MessageForm messageForm){
        Message message =modelMapper.map(messageForm,Message.class);
        BeanUtils.copyProperties(messageForm,message);
        messageService.save(message);
        return Result.success("新增成功");
    }

    /**
     *  删除聊天记录
     * @param id 聊天记录id
     * @return 删除结果
     */
    @Operation(summary = "删除聊天记录")
    @DeleteMapping("/delete/{id}")
    public Result<Object> deleteMessage(@PathVariable(value = "id") Long id){
        messageService.removeById(id);
        return Result.success("删除成功");
    }

    /**
     *  根据主键id修改聊天记录
     * @param id 聊天记录id
     * @param messageForm 聊天记录表单
     * @return 修改结果
     */
    @Operation(summary = "修改聊天记录")
    @PutMapping("/update/{id}")
    public Result<Object> updateMessage(@PathVariable(value = "id") Long id, @RequestBody MessageForm messageForm){
        // 检查数据库中是否存在对应的id
        Message existingMessage = messageService.getById(id);
        if (existingMessage == null) {
            return Result.failed("聊天记录不存在, 无法修改");
        }

        // 根据主键id修改聊天记录
        Message message = modelMapper.map(messageForm, Message.class);
        message.setId(id);
        messageService.updateById(message);
        return Result.success("修改成功");
    }
}
